﻿Imports SwDocumentMgr
Imports SwDocumentMgr.SwDmDocumentType
Imports SwDocumentMgr.SwDmCustomInfoType

Imports SolidWorks.Interop.sldworks
Imports SolidWorks.Interop.swconst

Imports SolidWorks.Interop.swconst.swUserPreferenceToggle_e
Imports SolidWorks.Interop.swconst.swUserPreferenceIntegerValue_e
Imports SolidWorks.Interop.swconst.swUserPreferenceStringListValue_e
Imports SolidWorks.Interop.swconst.swUserPreferenceDoubleValue_e
Imports SolidWorks.Interop.swconst.swSaveAsVersion_e
Imports SolidWorks.Interop.swconst.swMessageBoxIcon_e
Imports SolidWorks.Interop.swconst.swMessageBoxBtn_e
Imports SolidWorks.Interop.swconst.swSaveAsOptions_e
Imports SolidWorks.Interop.swconst.swDocumentTypes_e

Imports System
Imports System.Diagnostics
Imports SolidWorks.Interop

Module SW

    '  Public Const Custom_Properties_File = "C:\Program Files\SolidWorks\lang\chinese-simplified\properties.txt"
    Public Custom_Properties_File As String


    ' 自定义属性
    Public Structure CustomProperty
        Public Name As String       '名称
        Public LinkedTo As String   '链接
        Public Value As String      '值
        Public Evaluated As String  '评估值
    End Structure

    'sld文件结构
    Public Structure SLDDRW_File
        Public Parent_Folder As String      '父文件夹
        Public Part_Name As String        '文件名（零件名称）
        Public Slddrw_File_Name As String    '工程图文件名
        Public Sldprt_File_Name As String    '零件图文件名
        Public Dwg_File_Name As String       'cad文件名
        Public CustomPropertyCount As Short              '自定义属性长度
        Public CustomProperty() As CustomProperty        '自定义属性数组
    End Structure

    '排序
    Public Structure PaiXu
        Public FileFullName As String       '文件名
        Public PartNumber As String     '图号
    End Structure

    '图标索引
    Public Structure NodeIconText
        Public IconIndex As Integer      '图标索引
        Public TextForeColor As Color       '文字颜色
    End Structure

    '图层
    Public Structure LayerA
        Public Name As String           '名称
        Public Color As Integer         '颜色
        Public Description As String    '说明
        Public GetID As Integer         '
        Public Style As Integer         '样式
        Public Visible As Boolean       '可见性
        Public Width As Integer         '宽度
    End Structure


    Public Const LicnceKey = ""
    Public Const DRW = ".SLDDRW"
    Public Const PRT = ".SLDPRT"
    Public Const ASM = ".SLDASM"
    Public Const DWG = ".DWG"
    Public Const PDF = ".PDF"

    Public Const AppTitle = "SW扩展工具 For SolidWorks2007"
    Public Const WW = "http://www.taobao.com/webww/?spm=a1z10.1.0.0.DhBvcB&ver=1&touid=cntaobaoleaky114&siteid=cntaobao&status=1&portalId=&gid=&itemsId="
    Public Const Qzone = "http://20300140.qzone.qq.com"
    Public Const Taobao = "http://100114.taobao.com"
    public Const BaiDuPan="http://pan.baidu.com/s/1c048edi"
    Public Const swweb = "http://www.solidworks.com.cn/"
    Public Const GoogleCode = "http://code.google.com/p/swtool/"
    Public Const UpdateiniUrl = "http://swtool.googlecode.com/svn/SwToolUpdate.ini"
    Public Const Taobao_SW2007 = "http://item.taobao.com/item.htm?spm=a1z10.5.w4002-3957518072.14.h2dHnk&id=35124919581"
    Public Const Taobao_SW2012 = "http://item.taobao.com/item.htm?spm=a1z10.5.w4002-3957518072.11.0WHQvw&id=35592998486"

    Public IsReg As Boolean    '是否注册标记

    Public SwVersion As Short   'sw版本号

    Public IsGetNo As String     '添加文件时是否获取图号
    Public Ini_File As String   'ini 文件
    Public RF_File As String  '最近的文件夹
    Public Favor_File As String  '收藏夹
    Public Part_Number As String    '图号映射
    Public Printer As String    '打印机名称
    Public CAD_To As Short  '另存为dwg到自定义文件夹
    Public DoModel As String    '模式
    Public CAD_Add_Part_NO As Short '另存为dwg是否添加 图号
    Public Compear As Short '零件模式对比方式 全路径 or 文件名
    Public Review As CheckState '是否预览
    Public IsTopMost As Boolean  '主窗口是否在前
    Public AutoUpdate As Short   '自动更新

    Public A_SLDDRWFile As SLDDRW_File  '实例化 SLDDRW_File

    Public Copyed_SLDDRWFile As SLDDRW_File  '复制的文件属性
    Public Copyed_CustomProperty As CustomProperty  '复制的一个文件属性

    Public CustomPropertyNames() As String   '实例化 CustomPropertyNames数组

    'Public swApp As SldWorks
    'Public swModel As ModelDoc2

    Public Enum swDwgTemplates_e
        swDwgTemplateAsize = 0
        swDwgTemplateAsizeVertical = 1
        swDwgTemplateBsize = 2
        swDwgTemplateCsize = 3
        swDwgTemplateDsize = 4
        swDwgTemplateEsize = 5
        swDwgTemplateA4size = 6
        swDwgTemplateA4sizeVertical = 7
        swDwgTemplateA3size = 8
        swDwgTemplateA2size = 9
        swDwgTemplateA1size = 10
        swDwgTemplateA0size = 11
        swDwgTemplateCustom = 12
        swDwgTemplateNone = 13
    End Enum

    Public Enum swDwgPaperSizes_e
        swDwgPaperAsize = 0
        swDwgPaperAsizeVertical = 1
        swDwgPaperBsize = 2
        swDwgPaperCsize = 3
        swDwgPaperDsize = 4
        swDwgPaperEsize = 5
        swDwgPaperA4size = 6
        swDwgPaperA4sizeVertical = 7
        swDwgPaperA3size = 8
        swDwgPaperA2size = 9
        swDwgPaperA1size = 10
        swDwgPaperA0size = 11
        swDwgPapersUserDefined = 12
    End Enum

    Public Enum swDrawingViewTypes_e
        swDrawingSheet = 1
        swDrawingSectionView = 2
        swDrawingDetailView = 3
        swDrawingProjectedView = 4
        swDrawingAuxiliaryView = 5
        swDrawingStandardView = 6
        swDrawingNamedView = 7
        swDrawingRelativeView = 8
    End Enum

    Public Enum swDocumentTypes_e
        swDocNONE = 0       '  Used to be TYPE_NONE
        swDocPART = 1       '  Used to be TYPE_PART
        swDocASSEMBLY = 2   '  Used to be TYPE_ASSEMBLY
        swDocDRAWING = 3    '  Used to be TYPE_DRAWING
    End Enum

    Public Enum swUserPreferenceStringValue_e
        swFileLocationsDocumentTemplates = 6
        swFileLocationsSheetFormat = 7
        swDefaultTemplatePart = 8
        swDefaultTemplateAssembly = 9
        swDefaultTemplateDrawing = 10
    End Enum

    Public Enum swLineStyles_e
        swLineCONTINUOUS = 0
        swLineHIDDEN = 1
        swLinePHANTOM = 2
        swLineCHAIN = 3
        swLineCENTER = 4
        swLineSTITCH = 5
        swLineCHAINTHICK = 6
        swLineDEFAULT = 7
    End Enum

    Public Enum swLineWeights_e
        swLW_NONE = -1
        swLW_THIN = 0
        swLW_NORMAL = 1
        swLW_THICK = 2
        swLW_THICK2 = 3
        swLW_THICK3 = 4
        swLW_THICK4 = 5
        swLW_THICK5 = 6
        swLW_THICK6 = 7
        swLW_NUMBER = 8
        swLW_LAYER = 9
    End Enum


    '打印(文件名,打印机,份数)
    Public Sub PrintDrawing(ByVal FileFullName As String, ByVal Printer As String, ByVal Copies As Integer)
        On Error Resume Next

        Dim swApp As SldWorks
        Dim swModel As ModelDoc2

        swApp = CreateObject("SldWorks.Application")

        swApp.Visible = False

        swApp.OpenDoc(FileFullName, swDocDRAWING)
        swModel = swApp.ActiveDoc

        swModel.PrintOut(0, 0, Copies, False, Printer, 0, False)

        swApp.CloseDoc(FileFullName)

    End Sub

    '更改文件扩展名(源文件名,替换的扩展名)
    Public Function ChangeFileExe(ByVal FileFullName As String, ByVal ToExe As String) As String
        Dim FileExeName As String
        FileExeName = GetFileExtension(FileFullName)
        ChangeFileExe = Strings.Replace(FileFullName, FileExeName, ToExe, , , CompareMethod.Text)       
    End Function

    '获取子级装配关系(TreeNode,文件名)
    Public Sub Get_Depend(ByVal ObjectTN As TreeNode, ByVal FileName As String)
        Dim Node As TreeNode
        Dim vDepend As Object
        Dim SubName As String
        Dim SubFullName As String
        Dim KeyIndex As Integer
        Dim NIT As NodeIconText

        Dim swApp As SldWorks
        swApp = CreateObject("SldWorks.Application")

        KeyIndex = ObjectTN.Index
        vDepend = Nothing

        '获取最高级子集
        vDepend = swApp.GetDocumentDependencies2(FileName, False, True, False)

        If vDepend Is Nothing = False Then
            For Index = 0 To (UBound(vDepend) - 1) / 2
                SubName = vDepend(2 * Index)   '简名
                SubFullName = vDepend(2 * Index + 1)  '全名

                NIT = GetImageIndex(SubFullName, IsInSameFolder(FileName, SubFullName))
                '子级为asm 和 文件名为 asm
                If GetFileExtension(SubFullName) = ASM And GetFileExtension(FileName) = ASM Then

                    Node = ObjectTN.Nodes.Add("", SubName, NIT.IconIndex, NIT.IconIndex)
                    Node.ToolTipText = SubFullName
                    Node.ForeColor = NIT.TextForeColor
                    Get_Depend(Node, SubFullName)

                    'ElseIf GetFileExtension(SubFullName) = ASM Then            '   父文件为
                    '    Icon_Index = 0
                    '    If IsFileExsts(SubFullName) = False Then Icon_Index = 2
                    '    Nod = ObjectTN.Nodes.Add("", SubName, Icon_Index, Icon_Index)
                    '    Nod.ToolTipText = SubFullName
                    
                '子级为prt 
                ElseIf GetFileExtension(SubFullName) = PRT Then
                    'NodeIconText = GetImageIndex(SubFullName, IsInSameFolder(FileName, SubFullName))

                    Node = ObjectTN.Nodes.Add("", SubName, NIT.IconIndex, NIT.IconIndex)
                    Node.ToolTipText = SubFullName
                    Node.ForeColor = NIT.TextForeColor
                    Get_Depend(Node, SubFullName)
                    
                '子级为drw 
                ElseIf GetFileExtension(FileName) = DRW Then
                    'NodeIconText = GetImageIndex(SubFullName, IsInSameFolder(FileName, SubFullName))

                    Node = ObjectTN.Nodes.Add("", SubName, NIT.IconIndex, NIT.IconIndex)
                    Node.ToolTipText = SubFullName
                    Node.ForeColor = NIT.TextForeColor
                End If

            Next Index
        End If
    End Sub

    '修改关联(TreeView对象,被选择的源文件TreeNode,日志ListView对象,新文件)
    Public Function ChangeReferencedFile(ByVal ObjectTV As TreeView, ByVal Node As TreeNode, ByVal ObjectMessageLV As ListView, ByVal NewFileName As String) As Boolean

        Dim Old_File As SLDDRW_File = Nothing
        Dim New_File As SLDDRW_File = Nothing
        Dim Nit As NodeIconText
        Dim Message As String

        Dim swApp As SldWorks
        swApp = CreateObject("SldWorks.Application")

        New_File.Part_Name = NewFileName

        Old_File.Part_Name = Node.Text
        Old_File.Sldprt_File_Name = Node.ToolTipText
        Old_File.Slddrw_File_Name = ChangeFileExe(Old_File.Sldprt_File_Name, DRW)

        New_File.Sldprt_File_Name = Replace(Old_File.Sldprt_File_Name, Old_File.Part_Name & GetFileExtension(Old_File.Sldprt_File_Name), New_File.Part_Name & GetFileExtension(Old_File.Sldprt_File_Name))

        '新文件不存在，更改模型文件名
        If ReFileName(Old_File.Sldprt_File_Name, New_File.Sldprt_File_Name) = True Then 
            Node.Text = New_File.Part_Name
            Node.ToolTipText = New_File.Sldprt_File_Name
            Nit = GetImageIndex(New_File.Sldprt_File_Name, IsInSameFolder(New_File.Sldprt_File_Name, Old_File.Sldprt_File_Name))
            Node.ImageIndex = Nit.IconIndex
            Node.ForeColor = Nit.TextForeColor
            Node.SelectedImageIndex = Node.ImageIndex

            Message = Date.Now
            Add_MessageLV(ObjectMessageLV, Message, Color.White)

            Message = "命名：" & Old_File.Sldprt_File_Name & "  -->  " & GetSingleName(New_File.Sldprt_File_Name)
            Add_MessageLV(ObjectMessageLV, Message, ReNameColor)
        Else
            MsgBox(New_File.Sldprt_File_Name & "已存在！", MsgBoxStyle.OkCancel)
            Exit Function
        End If


        New_File.Slddrw_File_Name = ChangeFileExe(New_File.Sldprt_File_Name, DRW)
        If IsFileExsts(Old_File.Slddrw_File_Name) = True Then
        '新文件不存在，更改工程图文件名
            ReFileName(Old_File.Slddrw_File_Name, New_File.Slddrw_File_Name) 

            Message = "命名：" & Old_File.Slddrw_File_Name & "  -->  " & GetSingleName(New_File.Slddrw_File_Name)
            Add_MessageLV(ObjectMessageLV, Message, ReNameColor)
            
            '更改工程图的参考关系
            swApp.ReplaceReferencedDocument(New_File.Slddrw_File_Name, Old_File.Sldprt_File_Name, New_File.Sldprt_File_Name)    

            Message = "关系：" & New_File.Slddrw_File_Name & "::" & GetSingleName(Old_File.Sldprt_File_Name) & "  -->  " & GetSingleName(New_File.Sldprt_File_Name)
            Add_MessageLV(ObjectMessageLV, Message, ReferencedColor)

        End If

        Dim ParentNode As TreeNode = Node.Parent
        '存在父节点修改关系
        If ParentNode Is Nothing = False Then        
            swApp.ReplaceReferencedDocument(ParentNode.ToolTipText, Old_File.Sldprt_File_Name, New_File.Sldprt_File_Name)

            Message = "关系：" & ParentNode.ToolTipText & "::" & GetSingleName(Old_File.Sldprt_File_Name) & "  -->  " & GetSingleName(New_File.Sldprt_File_Name)
            Add_MessageLV(ObjectMessageLV, Message, ReferencedColor)

        End If

        Dim ChdNode As TreeNode
        
        '存在子节点修改关系
        If Node.Nodes Is Nothing = False Then
            For Each ChdNode In Node.Nodes   
                swApp.ReplaceReferencedDocument(ChdNode.ToolTipText, Old_File.Sldprt_File_Name, New_File.Sldprt_File_Name)

                Message = "关系：" & ChdNode.ToolTipText & "::" & GetSingleName(Old_File.Sldprt_File_Name) & "  -->  " & GetSingleName(New_File.Sldprt_File_Name)
                Add_MessageLV(ObjectMessageLV, Message, ReferencedColor)
            Next
        End If

        '遍历树中所有旧名及引用旧名的结节

        For Each Nodex As TreeNode In ObjectTV.Nodes
            Dim CompearStr(1) As String

            Select Case Compear
                Case 0                                              '文件名对比
                    CompearStr(0) = Nodex.Text
                    CompearStr(1) = Old_File.Part_Name
                Case 1                                                   '绝对地址对比
                    CompearStr(0) = Nodex.ToolTipText
                    CompearStr(1) = Old_File.Sldprt_File_Name

            End Select

            If CompearStr(0) = CompearStr(1) Then

                Nodex.Text = New_File.Part_Name
                Nodex.ToolTipText = New_File.Sldprt_File_Name

                Nit = GetImageIndex(New_File.Sldprt_File_Name, IsInSameFolder(New_File.Sldprt_File_Name, Old_File.Sldprt_File_Name))
                Nodex.ForeColor = Nit.TextForeColor
                Nodex.ImageIndex = Nit.IconIndex
                Nodex.SelectedImageIndex = Nodex.ImageIndex

                ParentNode = Nodex.Parent
                '存在父节点修改关系
                If ParentNode Is Nothing = False Then        
                    swApp.ReplaceReferencedDocument(ParentNode.ToolTipText, Old_File.Sldprt_File_Name, New_File.Sldprt_File_Name)

                    Message = "关系：" & ParentNode.ToolTipText & "::" & GetSingleName(Old_File.Sldprt_File_Name) & "  -->  " & GetSingleName(New_File.Sldprt_File_Name)
                    Add_MessageLV(ObjectMessageLV, Message, ReferencedColor)
                End If

            End If

            TraverseNodeReplaceReferencedDocument(ObjectMessageLV, Nodex, Old_File, New_File)
        Next

        ChangeReferencedFile = True

    End Function

    '遍历 树 修改关联
    Public Sub TraverseNodeReplaceReferencedDocument(ByVal ObjectMessageLV As ListView, ByVal ObjectTN As TreeNode, ByVal Old_File As SLDDRW_File, ByVal New_File As SLDDRW_File)

        Dim Nodex As TreeNode
        Dim ParentNodex As TreeNode
        Dim CompearStr(1) As String
        Dim Message As String
        Dim Nit As NodeIconText

        Dim swApp As SldWorks
        swApp = CreateObject("SldWorks.Application")

        For Each Nodex In ObjectTN.Nodes
            '---------------------------------------------------------------
            Debug.Print(Nodex.Text)

            Select Case Compear
                Case 0                                              '文件名对比
                    CompearStr(0) = Nodex.Text
                    CompearStr(1) = Old_File.Part_Name
                Case 1                                                   '绝对地址对比
                    CompearStr(0) = Nodex.ToolTipText
                    CompearStr(1) = Old_File.Sldprt_File_Name
            End Select


            'If Nodex.Text = Old_File.Part_Name Then              '文件名对比
            'If Nodex.ToolTipText = Old_File.Sldprt_File_Name Then           '绝对地址对比

            If CompearStr(0) = CompearStr(1) Then
                Nodex.Text = New_File.Part_Name
                Nodex.ToolTipText = New_File.Sldprt_File_Name
                Nit = GetImageIndex(New_File.Sldprt_File_Name, IsInSameFolder(New_File.Sldprt_File_Name, Old_File.Sldprt_File_Name))
                Nodex.ForeColor = Nit.TextForeColor
                Nodex.ImageIndex = Nit.IconIndex
                Nodex.SelectedImageIndex = Nodex.ImageIndex

                ParentNodex = Nodex.Parent
                '存在父节点修改关系
                If ParentNodex Is Nothing = False Then        
                    swApp.ReplaceReferencedDocument(ParentNodex.ToolTipText, Old_File.Sldprt_File_Name, New_File.Sldprt_File_Name)

                    Message = "关系：" & ParentNodex.ToolTipText & "::" & GetSingleName(Old_File.Sldprt_File_Name) & "  -->  " & GetSingleName(New_File.Sldprt_File_Name)
                    Add_MessageLV(ObjectMessageLV, Message, ReferencedColor)
                End If

            End If

            '-----------------------------------------------------------------
            TraverseNodeReplaceReferencedDocument(ObjectMessageLV, Nodex, Old_File, New_File)
        Next
    End Sub

    '替换文件
    Public Function ReplaceFile(ByVal ObjectTV As TreeView, ByVal Node As TreeNode, ByVal ObjectMessageLV As ListView, ByVal NewFileName As String) As Boolean

        Dim Old_File As SLDDRW_File = Nothing
        Dim New_File As SLDDRW_File = Nothing
        Dim Nit As NodeIconText
        Dim Message As String

        Dim swApp As SldWorks
        swApp = CreateObject("SldWorks.Application")

        New_File.Sldprt_File_Name = NewFileName
        New_File.Part_Name = GetOnlyname(New_File.Sldprt_File_Name)

        Old_File.Part_Name = Node.Text
        Old_File.Sldprt_File_Name = Node.ToolTipText

        Nit = GetImageIndex(New_File.Sldprt_File_Name, IsInSameFolder(Node.Parent.ToolTipText, New_File.Sldprt_File_Name))

        Node.ImageIndex = Nit.IconIndex
        Node.SelectedImageIndex = Nit.IconIndex
        Node.Text = New_File.Part_Name
        Node.ForeColor = Nit.TextForeColor
        Node.ToolTipText = New_File.Sldprt_File_Name

        Add_MessageLV(ObjectMessageLV, Date.Now, Color.AliceBlue)

        Message = "替换：" & Old_File.Sldprt_File_Name & "  -->  " & New_File.Part_Name
        Add_MessageLV(ObjectMessageLV, Message, ReplaceColor)

        Dim ParentNode As TreeNode = Node.Parent
        '存在父节点修改关系
        If ParentNode Is Nothing = False Then        
            swApp.ReplaceReferencedDocument(ParentNode.ToolTipText, Old_File.Sldprt_File_Name, New_File.Sldprt_File_Name)

            Message = "关系：" & ParentNode.ToolTipText & "::" & GetSingleName(Old_File.Sldprt_File_Name) & "  -->  " & GetSingleName(New_File.Sldprt_File_Name)
            Add_MessageLV(ObjectMessageLV, Message, ReferencedColor)

        End If
        '父节点不是 工程图 刷新关系
        If GetFileExtension(ParentNode.ToolTipText) <> DRW Then        
            Node.Nodes.Clear()
            Get_Depend(Node, New_File.Sldprt_File_Name)
        End If

        'Dim ChdNode As TreeNode
        'If Node.Nodes Is Nothing = False Then
        '    For Each ChdNode In Node.Nodes   '存在子节点修改关系
        '        swApp.ReplaceReferencedDocument(ChdNode.ToolTipText, Old_File.Sldprt_File_Name, New_File.Sldprt_File_Name)
        '        ObjectLlistBox.Items.Add("关系：" & ChdNode.ToolTipText & "::" & Old_File.Part_Name & "  -->  " & New_File.Part_Name)
        '    Next
        'End If

        '遍历树中所有旧名及引用旧名的结节

        'For Each Nodex In ObjectTV.Nodes
        '    If Nodex.ToolTipText = Old_File.Sldprt_File_Name Then
        '        Nodex.text = New_File.Part_Name
        '        Nodex.tooltiptext = New_File.Sldprt_File_Name

        '        ParentNode = Nodex.Parent
        '        If ParentNode Is Nothing = False Then        '存在父节点修改关系
        '            swApp.ReplaceReferencedDocument(ParentNode.ToolTipText, Old_File.Sldprt_File_Name, New_File.Sldprt_File_Name)
        '            ObjectLlistBox.Items.Add("关系：" & ParentNode.ToolTipText & "::" & Old_File.Part_Name & "  -->  " & New_File.Part_Name)
        '        End If

        '    End If

        'TraverseNode(ObjectLlistBox, Node, Old_File, New_File)
        'Next

        ReplaceFile = True

    End Function

    '获取文件图标号
    Public Function GetImageIndex(ByVal FileName As String, ByVal IsInSameFolder As Boolean) As NodeIconText

        If IsFileExsts(FileName) = False Then
            GetImageIndex.IconIndex = 6
            GetImageIndex.TextForeColor = Color.Red
            Exit Function
        End If
'父子文件在同级目录
        If IsInSameFolder = True Then                    
            GetImageIndex.TextForeColor = Color.Black
            Select Case GetFileExtension(FileName)
                Case ASM
                    GetImageIndex.IconIndex = 0
                Case PRT
                    GetImageIndex.IconIndex = 2
                Case DRW
                    GetImageIndex.IconIndex = 4
                Case Else
                    GetImageIndex.IconIndex = 6
            End Select
            Exit Function
        Else    
            '子文件不在父文件目录                                  
            GetImageIndex.TextForeColor = Color.Red
            Select Case GetFileExtension(FileName)
                Case ASM
                    GetImageIndex.IconIndex = 1
                Case PRT
                    GetImageIndex.IconIndex = 3
                Case DRW
                    GetImageIndex.IconIndex = 5
                Case Else
                    GetImageIndex.IconIndex = 6
            End Select
            Exit Function
        End If

    End Function

    '自动修复关系
    Public Sub Auto_Repair_Link(ByVal ObjectTV As TreeView, ByVal ObjectMessageLV As ListView, ByVal Node As TreeNode)

        Dim Nodex As TreeNode
        Dim Search_Nodex As TreeNode
        Dim Message As String
        Dim Nit As NodeIconText

        Dim swApp As SldWorks
        swApp = CreateObject("SldWorks.Application")

        For Each Nodex In Node.Nodes
            If IsFileExsts(Nodex.ToolTipText) = False Then
                Debug.Print(Nodex.Text)
                For Each Search_Nodex In ObjectTV.Nodes
                    If Nodex.Text = Search_Nodex.Text Then
                        'If MsgBox("是否将:   " & Nodex.Parent.ToolTipText & "::" & GetName(Nodex.ToolTipText) & vbCrLf & "修复为:   " & Search_Nodex.ToolTipText, MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                        swApp.ReplaceReferencedDocument(Nodex.Parent.ToolTipText, Nodex.ToolTipText, Search_Nodex.ToolTipText)

                        Nit = GetImageIndex(Search_Nodex.ToolTipText, IsInSameFolder(Nodex.Parent.ToolTipText, Search_Nodex.ToolTipText))
                        Nodex.ForeColor = Nit.TextForeColor
                        Nodex.ImageIndex = Nit.IconIndex
                        Nodex.SelectedImageIndex = Nit.IconIndex
                        Nodex.ForeColor = Nit.TextForeColor
                        Message = "关系：" & Nodex.Parent.ToolTipText & "::" & GetSingleName(Nodex.ToolTipText) & "  -->  " & Search_Nodex.ToolTipText
                        Add_MessageLV(ObjectMessageLV, Date.Now, Color.AliceBlue)
                        Add_MessageLV(ObjectMessageLV, Message, ReferencedColor)
                        Exit For
                        'End If
                    End If
                Next
            End If
            Auto_Repair_Link(ObjectTV, ObjectMessageLV, Nodex)
        Next
    End Sub

    '获取自定义属性 填充到 listview
    Public Function ReFreshCustomProperty(ByVal SldDrwFile As SLDDRW_File, ByVal LV As ListView) As SLDDRW_File

        Dim i As Short

        SldDrwFile = GetCustomPropertys(SldDrwFile, True)

        LV.BeginUpdate()
        LV.Items.Clear()
        If SldDrwFile.CustomPropertyCount > 0 Then


            For i = 0 To SldDrwFile.CustomPropertyCount
                Dim LVI As New ListViewItem(SldDrwFile.CustomProperty(i).Name)
                LVI.SubItems.Add(SldDrwFile.CustomProperty(i).Evaluated)
                LVI.SubItems.Add("")
                LV.Items.Add(LVI)
            Next
        End If
        'LV.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
        Set_LV_Color(LV, Color.BlanchedAlmond, Color.White)
        LV.EndUpdate()
        ReFreshCustomProperty = SldDrwFile

    End Function

    '生成新 工程图文件
    Public Function CreateNewDrawing(ByVal PrtFileFullName As String) As Boolean

        Dim Ini As New Ini
        Dim nRetval As Long
        Dim swApp As SldWorks
        Dim swModel As ModelDoc2
        Dim swDraw As DrawingDoc

        Dim Templates_DrwDot As String   ' "C:\Program Files\SolidWorks\data\templates\leaky.drwdot"
        Dim DrwFileFullName As String = Nothing

        Templates_DrwDot = Ini.INIRead(Ini_File, "SwTool", "Templates_DrwDot")
        If Templates_DrwDot = "" Then
            Return False
            Exit Function
        End If

        swApp = CreateObject("SldWorks.Application")

        PrtFileFullName = UCase(PrtFileFullName)
        Select Case GetFileExtension(PrtFileFullName)
            Case PRT 
                swModel = swApp.OpenDoc(PrtFileFullName, swDocPART)
                DrwFileFullName = ChangeFileExe(PrtFileFullName,  DRW)
            Case ASM
                swModel = swApp.OpenDoc(PrtFileFullName, swDocASSEMBLY)
                DrwFileFullName = ChangeFileExe(PrtFileFullName,  DRW)
            Case Else
                Exit Function
        End Select


        If swModel Is Nothing Then
            Exit Function
        Else
            swModel = swApp.ActivateDoc2(PrtFileFullName, True, nRetval)
            swApp.Visible = True
        End If

        swDraw = swApp.NewDocument(Templates_DrwDot, swDwgPaperSizes_e.swDwgPaperA4size, 0.0#, 0.0#)

        swDraw.InsertModelInPredefinedView(PrtFileFullName)

        swDraw.SaveAs2(DrwFileFullName, 0, False, False)

        swApp.CloseDoc(DrwFileFullName)
        swApp.CloseDoc(PrtFileFullName)

        If IsFileExsts(DrwFileFullName) = True Then
            CreateNewDrawing = True
        Else
            Return False
        End If

    End Function

    '更改图纸格式
    Public Function SetUpDrawingSheet(ByVal DrwFileFullName As String, ByVal Templates_Slddrt As String) As Boolean

        'Const sTemplatePath As String = "c:\Program Files\SolidWorks\data\b-landscape.slddrt"
        Dim swApp As SldWorks
        Dim swModel As ModelDoc2
        Dim swDraw As DrawingDoc
        Dim swSheet As Sheet
        Dim nRetval As Boolean

        Dim SheetScaleScaleNumerator As Double  '比例尺分子
        Dim SheetScaleScaleDenominator As Double    '比例尺分母
        Dim FirstAngle As Boolean

        swApp = CreateObject("SldWorks.Application")
        swModel = swApp.OpenDoc(DrwFileFullName, swDocDRAWING)
        swModel = swApp.ActiveDoc

        swApp.Visible = False

        swDraw = swModel
        swSheet = swDraw.GetCurrentSheet

        If UCase(swSheet.GetTemplateName) = UCase(Templates_Slddrt) Then
            swApp.CloseDoc(DrwFileFullName)
            Return False
            Exit Function
        End If

        Dim A = swSheet.GetProperties

        'The return value is the following array of seven doubles:
        ' [ paperSize, templateIn, scale1, scale2, firstAngle, width, height ]
        'where:
        'paperSize = Paper size. This value is a long packed into a double and is represented by the swDwgPaperSizes_e enumeration.
        'templateIn = Template index. This value is a long packed into a double and is represented by the swDwgTemplates_e enumeration.
        'scale1 = Scale numerator.
        'scale2 = Scale denominator.
        'firstAngle = Value is a boolean packed into a double and returns TRUE if the sheet is using first angle projection and FALSE if not.
        'width = Paper width.
        'height = Paper height.

        SheetScaleScaleNumerator = A(2)
        SheetScaleScaleDenominator = A(3)
        FirstAngle = A(4)

        'nRetval = swDraw.SetupSheet4(swSheet.GetName, swDwgPaperSizes_e.swDwgPaperBsize, swDwgTemplates_e.swDwgTemplateBsize, 1.0#, 1.0#, False, Templates_Slddrt, 0.0#, 0.0#, "")
        nRetval = swDraw.SetupSheet4(swSheet.GetName, swDwgPaperSizes_e.swDwgPapersUserDefined, swDwgTemplates_e.swDwgTemplateCustom, SheetScaleScaleNumerator, SheetScaleScaleDenominator, FirstAngle, Templates_Slddrt, 0.0#, 0.0#, "")


        swModel.ForceRebuild3(False)

        swDraw.SaveAs2(DrwFileFullName, 0, False, False)
        swApp.CloseDoc(DrwFileFullName)

        Return nRetval

    End Function

    '判断是否为某个类型的sw文件
    Public Function IsSWFile(ByVal FileFullName As String, ByVal Extensions As String) As Boolean
        Dim Exten As String
        Exten = UCase(GetFileExtension(FileFullName))
        If InStr(Extensions, Exten) <> 0 Then
            Return True
        Else
            Return False
        End If
    End Function
    
        '获取sw文件类型
    Public Function GetSWFileType(ByVal FileFullName As String) As swDocumentTypes_e
        Dim Exten As String
        Exten = UCase(GetFileExtension(FileFullName))
        Select case Exten
            Case ASM
                Return swDocumentTypes_e.swDocASSEMBLY
            Case PRT
                Return swDocumentTypes_e.swDocPART
            Case DRW
                Return swDocumentTypes_e.swDocDRAWING
            Case Else
                Return swDocumentTypes_e.swDocNONE
        End Select
    End Function

    '获取图层
    Public Function GeyLayers(ByVal FileFullName As String) As LayerA()
        Dim swApp As SldWorks
        Dim swModel As ModelDoc2
        Dim swLayerMgr As LayerMgr
        Dim vLayerArr As Object
        Dim vLayer As Object
        Dim swLayer As Layer
        Dim LayerArr(10) As LayerA
        Dim i As Integer

        swApp = CreateObject("SldWorks.Application")

        swModel = swApp.OpenDoc(FileFullName, swDocDRAWING)
        swModel = swApp.ActiveDoc
        swApp.Visible = False

        swLayerMgr = swModel.GetLayerManager
        'Debug.Print("File = " & swModel.GetPathName)
        'Debug.Print("  Current Layer = " & swLayerMgr.GetCurrentLayer)
        'Debug.Print("")

        vLayerArr = swLayerMgr.GetLayerList
        ReDim LayerArr(swLayerMgr.GetCount - 1)
        i = 0

        For Each vLayer In vLayerArr
            swLayer = swLayerMgr.GetLayer(vLayer)
            'Debug.Print("  " & swLayer.Name)
            'Debug.Print("    Color          = " & swLayer.Color)
            'Debug.Print("    Description    = " & swLayer.Description)
            'Debug.Print("    GetId          = " & swLayer.GetID)
            'Debug.Print("    Style          = " & swLayer.Style)
            'Debug.Print("    Visible        = " & swLayer.Visible)
            'Debug.Print("    Width          = " & swLayer.Width)

            LayerArr(i).name = swLayer.Name
            LayerArr(i).Color = swLayer.Color
            LayerArr(i).Description = swLayer.Description
            LayerArr(i).Style = swLayer.Style
            LayerArr(i).Visible = swLayer.Visible
            LayerArr(i).Width = swLayer.Width
            i = i + 1
        Next

        swApp.CloseDoc(FileFullName)

        Return LayerArr
    End Function

    '设置图层
    Public Sub SetLayer(ByVal FileFullName As String, ByVal LayerArr() As LayerA)
        Dim swApp As SldWorks
        Dim swModel As ModelDoc2
        Dim swLayerMgr As LayerMgr
        Dim swLayer As Layer

        swApp = CreateObject("SldWorks.Application")

        swModel = swApp.OpenDoc(FileFullName, swDocDRAWING)
        swModel = swApp.ActiveDoc
        swApp.Visible = False
        swLayerMgr = swModel.GetLayerManager

        For Each Layer In LayerArr
            swLayer = swLayerMgr.GetLayer(Layer.Name)
            If swLayer Is Nothing Then
                swLayerMgr.AddLayer(Layer.Name, Layer.Description, Layer.Color, Layer.Style, Layer.Width)
            Else
                swLayer.Color = Layer.Color
                swLayer.Description = Layer.Description
                swLayer.Style = Layer.Style
                swLayer.Visible = Layer.Visible
                swLayer.Width = Layer.Width
            End If
        Next

        'swModel.ForceRebuild3(False)

        swModel.SaveAs2(FileFullName, 0, False, False)
        swApp.CloseDoc(FileFullName)
    End Sub

    '列举外部参考引用
    Public Function ListExternalFileReference(ByVal FileFullName As String) As Object
        On Error Resume Next
        Dim swApp As SldWorks
        Dim swModel As ModelDoc2
        Dim swModDocExt As ModelDocExtension
        Dim swSelMgr As SelectionMgr
        Dim swFeat As Feature
        Dim swComp As Component2
        Dim vModelPathName As Object = Nothing
        Dim vComponentPathName As Object = Nothing
        Dim vFeature As Object = Nothing
        Dim vDataType As Object = Nothing
        Dim vStatus As Object = Nothing
        Dim vRefEntity As Object = Nothing
        Dim vFeatComp As Object = Nothing
        Dim nConfigOpt As Integer
        Dim sConfigName As String = Nothing
        Dim nRefCount As Integer
        Dim nSelType As Integer
        Dim i As Integer

        If IsFileExsts(FileFullName) = False Then
            Return Nothing
            Exit Function
        End If

        swApp = CreateObject("SldWorks.Application")
        swModel = swApp.OpenDoc(FileFullName, swDocPART)
        swModel = swApp.ActiveDoc
        swApp.Visible = False

        swSelMgr = swModel.SelectionManager

        swModDocExt = swModel.Extension
        nSelType = swSelMgr.GetSelectedObjectType3(1, -1)


        Select Case nSelType

            ' Selected component in an assembly
            Case swSelectType_e.swSelCOMPONENTS
                swComp = swSelMgr.GetSelectedObjectsComponent3(1, -1)
                nRefCount = swComp.ListExternalFileReferencesCount
                swComp.ListExternalFileReferences2(vModelPathName, vComponentPathName, vFeature, vDataType, vStatus, vRefEntity, vFeatComp, nConfigOpt, sConfigName)

                swModel = swComp.GetModelDoc2

                ' Selected feature in a part or assembly
            Case swSelectType_e.swSelBODYFEATURES, swSelectType_e.swSelSKETCHES
                swFeat = swSelMgr.GetSelectedObject6(1, -1)
                nRefCount = swFeat.ListExternalFileReferencesCount
                swFeat.ListExternalFileReferences2(vModelPathName, vComponentPathName, vFeature, vDataType, vStatus, vRefEntity, vFeatComp, nConfigOpt, sConfigName)


                ' Part document only
            Case Else
                nRefCount = swModDocExt.ListExternalFileReferencesCount
                swModDocExt.ListExternalFileReferences(vModelPathName, vComponentPathName, vFeature, vDataType, vStatus, vRefEntity, vFeatComp, nConfigOpt, sConfigName)

        End Select


        Debug.Print("Model name = " + swModel.GetPathName)
        Debug.Print("    Reference count        = " + Str(nRefCount))
        Debug.Print("")
        'For i = 0 To nRefCount - 1
        '    Debug.Print("    Model path + name      = " + vModelPathName(i))
        '    Debug.Print("    Component path + name  = " + vComponentPathName(i))
        '    Debug.Print("    Feature                = " + vFeature(i))
        '    Debug.Print("    Data type              = " + vDataType(i))
        '    Debug.Print("    Status                 = " + Str(vStatus(i)))
        '    Debug.Print("    Reference entity       = " + vRefEntity(i))
        '    Debug.Print("    Feature component      = " + vFeatComp(i))
        'Next i

        'Debug.Print("    Configuration option   = " & nConfigOpt)
        'Debug.Print("    Configuration name     = " & sConfigName)
        'Debug.Print("")

        swApp.CloseDoc(FileFullName)

        Return vModelPathName
    End Function

    '遍历指定node，返回外部参考和node比较，有不同的就提示
    Public Sub TraverseNodeListExternalFileReference(ByVal ObjectTN As TreeNode)
        Dim Nodex As TreeNode
        Dim ParentNodeFullName As String
        Dim ChildNodeFullName As String
        Dim vDependArr As Object

        Dim swApp As SldWorks

        swApp = CreateObject("SldWorks.Application")

        '父node 文件
        ParentNodeFullName = ObjectTN.ToolTipText.ToString

        For Each Nodex In ObjectTN.Nodes
            '---------------------------------------------------------------
            '子node文件
            ChildNodeFullName = Nodex.ToolTipText.ToString
            '列举 子node文件 外部参考引用
            vDependArr = ListExternalFileReference(ChildNodeFullName)
            For Each a In vDependArr
                If [Strings].StrComp(a.ToString, ParentNodeFullName) <> 0 Then
                    MsgBox("检查到：" & ChildNodeFullName & " 有断开的外部连接到： " & a, MsgBoxStyle.Information, "检查外部参考引用")
                    Exit For
                End If
            Next
            '-----------------------------------------------------------------
            TraverseNodeListExternalFileReference(Nodex)
        Next
    End Sub


End Module
